package com.ruoyi.edu.job;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.edu.api.domain.EduCourse;
import com.ruoyi.edu.service.IEduCourseService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程定时任务
 * 计算课程学习数和购买数
 *
 * @author isahino
 * @version 1.0
 * @date 2023/9/27 9:41
 */
@Service
public class CourseJobService {

    @Resource
    private IEduCourseService iEduCourseService;

    @Resource
    private RedisService redisService;

    /**
     * 每分钟定时执行任务一次
     * 从缓存中分析该时段内课程的观看及购买人数
     * 而后对课程表进行更新
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void countCourseData() {
        System.out.println("开始定时任务");
        // 查询出所有课程并转换为map结构便于操作
        Map<String, EduCourse> courseMap = iEduCourseService.list().stream().collect(Collectors.toMap(EduCourse::getId, c -> c));
        // 准备要更新的课程列表
        Map<String, EduCourse> updateMap = new HashMap<>(10);
        // 先统计学习次数
        Map<String, Object> viewCacheMap = redisService.getCacheMap(CacheConstants.VIDEO_VIEWS);
        if (viewCacheMap.size() != 0) {
            for (String courseId : viewCacheMap.keySet()) {
                EduCourse eduCourse = courseMap.get(courseId);
                eduCourse.setViewCount(eduCourse.getViewCount() + (Integer) viewCacheMap.get(courseId));
                updateMap.put(courseId, eduCourse);
                // 用完就扔
                redisService.deleteCacheMapValue(CacheConstants.VIDEO_VIEWS, courseId);
            }
        }
        // 统计购买次数
        Map<String, Object> buyCacheMap = redisService.getCacheMap(CacheConstants.VIDEO_BUYS);
        if (buyCacheMap.size() != 0) {
            for (String courseId : buyCacheMap.keySet()) {
                EduCourse eduCourse = courseMap.get(courseId);
                eduCourse.setBuyCount(eduCourse.getBuyCount() + (Integer) buyCacheMap.get(courseId));
                // 如果在更新学习次数阶段没有加入更新列表，则现在加入
                updateMap.putIfAbsent(courseId, eduCourse);
                // 用完就扔
                redisService.deleteCacheMapValue(CacheConstants.VIDEO_BUYS, courseId);
            }
        }
        // 批量更新
        iEduCourseService.updateBatchById(updateMap.values());
        System.out.println("定时任务结束，此次更新" + updateMap.size() + "条课程数据");
    }
}
